package com.fafa.pos.biz;

import com.fafa.pos.dao.*;
import com.fafa.pos.dao.impl.*;
import com.fafa.pos.pojo.*;
import com.fafa.pos.util.DateUtil;
import com.fafa.pos.util.WebServiceUtil;
import com.fafa.pos.util.WebServiceValueCastUtil;
import com.fafa.pos.vo.WSResult;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Zhou Bing on 2017/8/16.
 *
 * 复杂业务逻辑
 */
public class ComplexBiz {

    private IConfigDao configDao;
    private ICardInfoDao cardInfoDao;
    private IDateLimitRuleInfoDao dateLimitRuleInfoDao;
    private IPOSInfoDao POSInfoDao;
    private IUserInfoDao userInfoDao;
    private IVipGroupInfoDao vipGroupInfoDao;
    private IVipInfoDao vipInfoDao;
    private IConsumeInfoDao consumeInfoDao;

    public ComplexBiz(DBUtil dbUtil) {

        configDao = new ConfigDaoImpl(dbUtil);
        cardInfoDao = new CardInfoDaoImpl(dbUtil);
        dateLimitRuleInfoDao = new DateLimitRuleInfoDaoImpl(dbUtil);
        POSInfoDao = new POSInfoDaoImpl(dbUtil);
        userInfoDao = new UserInfoDaoImpl(dbUtil);
        vipGroupInfoDao = new VipGroupInfoDaoImpl(dbUtil);
        vipInfoDao = new VipInfoDaoImpl(dbUtil);
        consumeInfoDao = new ConsumeInfoDaoImpl(dbUtil);
    }


    /**
     * 判断此卡是否能够消费
     *
     * @param cardNo
     * @return
     */
    public boolean isSale(String cardNo) {

        CardInfo cardInfo = cardInfoDao.getCard(cardNo);
        VipInfo vipInfo = null;
        if (cardInfo != null) {
            vipInfo = vipInfoDao.getVipInfo(cardInfo.getVipId());
            if (vipInfo != null) {
                if ("10221001".equals(cardInfo.getCardStatus()) && "10251001".equals(vipInfo.getVipStatus()) && "1".equals(vipInfo.getVisible())) {//在白名单

                    if (DateUtil.getCurDateStr("yyyy-MM-dd HH:mm:ss").compareTo(cardInfo.getValidDate()) <= 0) {//卡有效

                        //查询该卡当天离线消费记录
                        List<ConsumeInfo> consumeInfos = consumeInfoDao.getCurDayOffLineConsumeInfo(cardNo);
                        double curOffLineSaleNum = 0, totalOffLineSaleNum = 0;//离线消费金额
                        int curOffLineSaleCount = 0, totalOffLineSaleCount = 0;//离线消费次数
                        boolean numEnable = false, countEnable = false;
                        if (consumeInfos != null) {
                            for (ConsumeInfo consumeInfo : consumeInfos) {
                                curOffLineSaleNum += Double.parseDouble(consumeInfo.getMoney());
                                curOffLineSaleCount++;
                            }
                        }
                        List<DateLimitRuleInfo> dateLimitRuleInfos = dateLimitRuleInfoDao.getDateLimitRuleInfo(vipInfo.getGroupId());
                        if (dateLimitRuleInfos != null) {
                            for (DateLimitRuleInfo dateLimitRuleInfo : dateLimitRuleInfos) {
                                if ("7".equals(dateLimitRuleInfo.getLimitType())) {//金额限制
                                    numEnable = true;
                                    totalOffLineSaleNum = Double.parseDouble(dateLimitRuleInfo.getLimitAmt());
                                } else if ("8".equals(dateLimitRuleInfo.getLimitType())) {//次数限制
                                    countEnable = true;
                                    totalOffLineSaleCount = Integer.parseInt(dateLimitRuleInfo.getLimitNum());
                                }
                            }
                        }

                        if(numEnable&&countEnable){//启用 消费 限制
                            if (curOffLineSaleNum <= totalOffLineSaleNum && curOffLineSaleCount <= totalOffLineSaleCount) {
                                return true;
                            } else {
                                System.out.println("消费金额/次数限制");
                                return false;
                            }
                        }else{
                            return  true;
                        }

                    } else {
                        System.out.println("卡无效");
                        return false;
                    }

                } else {
                    System.out.println("不在白名单");
                    return false;
                }
            } else {
                System.out.println("找不到对应的vipInfo");
                return false;
            }
        } else {
            System.out.println("找不到该cardInfo");
            return false;
        }

    }

    /**
     * 下载数据
     *
     * @return
     */
    public String downloadData() {

        String errorMessage = null;

        try {
            /*
                获得最后一次基础数据的更新时间,默认为1970-01-01 00:00:00:000
                默认下载10000+条
             */
            int downloadCNT = 10000;
            String cardInfoLastUpdateDate = "1970-01-01 00:00:00.000";
            String dateLimitRuleInfoLastUpdateDate = "1970-01-01 00:00:00.000";
            String posInfoLastUpdateDate = "1970-01-01 00:00:00.000";
            String userInfoLastUpdateDate = "1970-01-01 00:00:00.000";
            String vipGroupInfoLastUpdateDate = "1970-01-01 00:00:00.000";
            String vipInfoLastUpdateDate = "1970-01-01 00:00:00.000";
            Config config = configDao.getConfig();
            //TODO  修改
            if (config != null
                    && config.getProperties().get("T_CARDINFO_UPDATE_DATE") != null
                    && config.getProperties().get("T_DATELIMITRULEINFO_UPDATE_DATE") != null
                    && config.getProperties().get("T_POSINfO_UPDATE_DATE") != null
                    && config.getProperties().get("T_USERINFO_UPDATE_DATE") != null
                    && config.getProperties().get("T_VIPGROUPINFO_UPDATE_DATE") != null
                    && config.getProperties().get("T_VIPINFO_UPDATE_DATE") != null) {
                downloadCNT = 200;
            }
            if (config != null && config.getProperties().get("T_CARDINFO_UPDATE_DATE") != null && !"".equals(config.getProperties().get("T_CARDINFO_UPDATE_DATE").trim())) {
                cardInfoLastUpdateDate = config.getProperties().get("T_CARDINFO_UPDATE_DATE");
            }
            if (config != null && config.getProperties().get("T_DATELIMITRULEINFO_UPDATE_DATE") != null && !"".equals(config.getProperties().get("T_DATELIMITRULEINFO_UPDATE_DATE"))) {
                dateLimitRuleInfoLastUpdateDate = config.getProperties().get("T_DATELIMITRULEINFO_UPDATE_DATE");
            }
            if (config != null && config.getProperties().get("T_POSINfO_UPDATE_DATE") != null && !"".equals(config.getProperties().get("T_POSINfO_UPDATE_DATE").trim())) {
                posInfoLastUpdateDate = config.getProperties().get("T_POSINfO_UPDATE_DATE");
            }
            if (config != null && config.getProperties().get("T_USERINFO_UPDATE_DATE") != null && !"".equals(config.getProperties().get("T_USERINFO_UPDATE_DATE").trim())) {
                userInfoLastUpdateDate = config.getProperties().get("T_USERINFO_UPDATE_DATE");
            }
            if (config != null && config.getProperties().get("T_VIPGROUPINFO_UPDATE_DATE") != null && !"".equals(config.getProperties().get("T_VIPGROUPINFO_UPDATE_DATE").trim())) {
                vipGroupInfoLastUpdateDate = config.getProperties().get("T_VIPGROUPINFO_UPDATE_DATE");
            }
            if (config != null && config.getProperties().get("T_VIPINFO_UPDATE_DATE") != null && !"".equals(config.getProperties().get("T_VIPINFO_UPDATE_DATE").trim())) {
                vipInfoLastUpdateDate = config.getProperties().get("T_VIPINFO_UPDATE_DATE");
            }

            //1.下载用户数据
            System.out.println("上次userInfos更新时间" + userInfoLastUpdateDate);
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("cnt", downloadCNT);
            parameters.put("lastUpdateDate", userInfoLastUpdateDate);
            SoapObject so = WebServiceUtil.getResponse(config, "DownUserInfo", parameters, 1000 * 60 * 10);

            if (so != null) {
                SoapPrimitive sp = (SoapPrimitive) so.getProperty("DownUserInfoResult");
                WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                if (wsResult.getResultCode() == 0) {
                    //保存
                    List<UserInfo> userInfos = new ArrayList<UserInfo>();
                    List<Map<String, Object>> values = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                    for (Map<String, Object> map : values) {
                        UserInfo userInfo = new UserInfo();
                        userInfo.setUserId(map.get("USER_ID").toString());
                        userInfo.setUserCode(map.get("USER_CODE").toString());
                        userInfo.setUserName(map.get("USER_NAME").toString());
                        userInfo.setPassword(map.get("PASSWORD").toString());
                        userInfo.setStatus(map.get("STATUS").toString());
                        userInfo.setVisible(map.get("IS_VISIBLE").toString());
                        userInfo.setUpdate(map.get("UPDATE_DATE").toString());

                        //System.out.println("userInfo:" + userInfo.toString());

                        userInfos.add(userInfo);
                    }
                    System.out.println("下载userInfos信息：" + userInfos.size());
                    if (userInfos.size() > 0) {
                        userInfoDao.saveUserInfoList(userInfos);
                    }
                } else if (wsResult.getResultCode() == 3 || wsResult.getResultCode() == 4) {
                    errorMessage = wsResult.getResultValues().get("message").toString();
                }
            } else {
                errorMessage = "连接超时";
            }
            //2.下载会员分组数据
            System.out.println("上次vipGroupInfos更新时间" + vipGroupInfoLastUpdateDate);
            parameters.clear();
            parameters = new HashMap<>();
            parameters.put("cnt", downloadCNT);
            parameters.put("lastUpdateDate", vipGroupInfoLastUpdateDate);
            so = WebServiceUtil.getResponse(config, "DownVipGroupInfo", parameters, 1000 * 60 * 10);

            if (so != null) {
                SoapPrimitive sp = (SoapPrimitive) so.getProperty("DownVipGroupInfoResult");
                WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                if (wsResult.getResultCode() == 0) {
                    //保存
                    List<VipGroupInfo> vipGroupInfos = new ArrayList<VipGroupInfo>();
                    List<Map<String, Object>> values = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                    for (Map<String, Object> map : values) {
                        VipGroupInfo vipGroupInfo = new VipGroupInfo();
                        vipGroupInfo.setGroupId(map.get("GROUP_ID").toString());
                        vipGroupInfo.setGroupCode(map.get("GROUP_CODE").toString());
                        vipGroupInfo.setGroupName(map.get("GROUP_NAME").toString());
                        vipGroupInfo.setLevelId(map.get("LEVEL_ID").toString());
                        vipGroupInfo.setRate(map.get("RATE").toString());
                        vipGroupInfo.setStatus(map.get("STATUS").toString());
                        vipGroupInfo.setVisible(map.get("IS_VISIBLE").toString());
                        vipGroupInfo.setUpdate(map.get("UPDATE_DATE").toString());

                        //System.out.println("vipGroupInfo:" + vipGroupInfo.toString());

                        vipGroupInfos.add(vipGroupInfo);
                    }
                    System.out.println("下载vipGroupInfos信息：" + vipGroupInfos.size());
                    if (vipGroupInfos.size() > 0) {
                        vipGroupInfoDao.saveVipGroupInfoList(vipGroupInfos);
                    }
                } else if (wsResult.getResultCode() == 3 || wsResult.getResultCode() == 4) {
                    errorMessage = wsResult.getResultValues().get("message").toString();
                }

            } else {
                errorMessage = "连接超时";
            }

            //3.下载日期限制数据
            System.out.println("上次dateLimitRuleInfos更新时间" + dateLimitRuleInfoLastUpdateDate);
            parameters.clear();
            parameters = new HashMap<>();
            parameters.put("cnt", downloadCNT);
            parameters.put("lastUpdateDate", dateLimitRuleInfoLastUpdateDate);
            so = WebServiceUtil.getResponse(config, "DownDateLimitRuleInfo", parameters, 1000 * 60 * 10);

            if (so != null) {
                SoapPrimitive sp = (SoapPrimitive) so.getProperty("DownDateLimitRuleInfoResult");
                WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                if (wsResult != null) {
                    if (wsResult.getResultCode() == 0) {
                        //保存
                        List<DateLimitRuleInfo> dateLimitRuleInfos = new ArrayList<DateLimitRuleInfo>();
                        List<Map<String, Object>> values = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                        for (Map<String, Object> map : values) {


                            DateLimitRuleInfo dateLimitRuleInfo = new DateLimitRuleInfo();
                            dateLimitRuleInfo.setLimitId(map.get("LIMIT_ID").toString());
                            dateLimitRuleInfo.setLimitCode(map.get("LIMIT_CODE").toString());
                            dateLimitRuleInfo.setLimitName(map.get("LIMIT_NAME").toString());
                            dateLimitRuleInfo.setLimitType(map.get("LIMIT_TYPE").toString());
                            dateLimitRuleInfo.setAcctTypeId(map.get("ACCT_TYPE_ID").toString());
                            dateLimitRuleInfo.setGroupId(map.get("GROUP_ID").toString());
                            dateLimitRuleInfo.setLineId(map.get("LINE_ID").toString());
                            dateLimitRuleInfo.setPeriodId(map.get("PERIOD_ID").toString());
                            dateLimitRuleInfo.setLimitAmt(map.get("LIMIT_AMT").toString());
                            dateLimitRuleInfo.setLimitNum(map.get("LIMIT_NUM").toString());
                            dateLimitRuleInfo.setStatus(map.get("STATUS").toString());
                            dateLimitRuleInfo.setVisible(map.get("IS_VISIBLE").toString());
                            dateLimitRuleInfo.setUpdate(map.get("UPDATE_DATE").toString());

                            //System.out.println("dateLimitRuleInfo:" + dateLimitRuleInfo.toString());

                            dateLimitRuleInfos.add(dateLimitRuleInfo);
                        }
                        System.out.println("下载dateLimitRuleInfos信息：" + dateLimitRuleInfos.size());
                        if (dateLimitRuleInfos.size() > 0) {
                            dateLimitRuleInfoDao.saveDateLimitRuleInfoList(dateLimitRuleInfos);
                        }
                    } else if (wsResult.getResultCode() == 3 || wsResult.getResultCode() == 4) {
                        errorMessage = wsResult.getResultValues().get("message").toString();
                    }
                }
            } else {
                errorMessage = "连接超时";
            }

            //4.下载会员信息数据
            System.out.println("上次vipInfos更新时间" + vipInfoLastUpdateDate);
            parameters.clear();
            parameters = new HashMap<>();
            parameters.put("cnt", downloadCNT);
            parameters.put("lastUpdateDate", vipInfoLastUpdateDate);
            so = WebServiceUtil.getResponse(config, "DownVipInfo", parameters, 1000 * 60 * 10);

            if (so != null) {
                SoapPrimitive sp = (SoapPrimitive) so.getProperty("DownVipInfoResult");
                WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                if (wsResult != null) {
                    if (wsResult.getResultCode() == 0) {
                        //保存
                        List<VipInfo> vipInfos = new ArrayList<VipInfo>();
                        List<Map<String, Object>> values = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                        for (Map<String, Object> map : values) {

                            // vipId='1.0000049E7', vipCode='108120', vipName='Tsang, Ka Ki', vipStatus='1.0251001E7', groupId='1.0000001E7', visible='1.0', update='2017-07-17T18:26:31.663'}


                            VipInfo vipInfo = new VipInfo();
                            vipInfo.setVipId(new BigDecimal(map.get("VIP_ID").toString()).toPlainString());
                            vipInfo.setVipCode(map.get("VIP_CODE").toString());
                            vipInfo.setVipName(map.get("VIP_NAME").toString());
                            vipInfo.setVipStatus(new BigDecimal(map.get("VIP_STATUS").toString()).toPlainString());
                            vipInfo.setGroupId(new BigDecimal(map.get("GROUP_ID").toString()).toPlainString());
                            vipInfo.setVisible(map.get("IS_VISIBLE").toString().substring(0, 1));
                            vipInfo.setUpdate(map.get("UPDATE_DATE").toString().replaceAll("T", " "));

                            //System.out.println("vipInfo:" + vipInfo.toString());

                            vipInfos.add(vipInfo);
                        }
                        System.out.println("下载vipInfos信息：" + vipInfos.size());
                        if (vipInfos.size() > 0) {
                            vipInfoDao.saveVipInfoList(vipInfos);
                        }
                    } else if (wsResult.getResultCode() == 3 || wsResult.getResultCode() == 4) {
                        errorMessage = wsResult.getResultValues().get("message").toString();
                    }
                }
            } else {
                errorMessage = "连接超时";
            }
            //5.下载卡信息数据
            System.out.println("上次cardInfos更新时间" + cardInfoLastUpdateDate);
            parameters.clear();
            parameters = new HashMap<>();
            parameters.put("cnt", downloadCNT);
            parameters.put("lastUpdateDate", cardInfoLastUpdateDate);
            so = WebServiceUtil.getResponse(config, "DownCardInfo", parameters, 1000 * 60 * 10);

            if (so != null) {
                SoapPrimitive sp = (SoapPrimitive) so.getProperty("DownCardInfoResult");
                WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                if (wsResult.getResultCode() == 0) {
                    //保存
                    List<CardInfo> cardInfos = new ArrayList<CardInfo>();
                    List<Map<String, Object>> values = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                    for (Map<String, Object> map : values) {
                        //1001891

                        //cardId='1.001891E7', cardCode='1208362', cardStatus='1.0221001E7', vipId='1.001891E7', validDate='2044-02-19T00:00:00', update='2016-10-03T14:39:19'

                        CardInfo cardInfo = new CardInfo();
                        cardInfo.setCardId(new BigDecimal(map.get("CARD_ID").toString()).toPlainString());
                        cardInfo.setCardCode(map.get("CARD_CODE").toString());
                        cardInfo.setCardStatus(new BigDecimal(map.get("CARD_STATUS").toString()).toPlainString());
                        cardInfo.setVipId(new BigDecimal(map.get("VIP_ID").toString()).toPlainString());
                        cardInfo.setValidDate(map.get("VALID_DATE").toString().replaceAll("T", " "));
                        cardInfo.setUpdate(map.get("UPDATE_DATE").toString().replaceAll("T", " "));

                        //System.out.println("cardInfo:" + cardInfo.toString());

                        cardInfos.add(cardInfo);
                    }
                    System.out.println("下载cardInfos信息：" + cardInfos.size());
                    if (cardInfos.size() > 0) {
                        cardInfoDao.saveCardInfoList(cardInfos);
                    }
                } else if (wsResult.getResultCode() == 3 || wsResult.getResultCode() == 4) {
                    errorMessage = wsResult.getResultValues().get("message").toString();
                }

            } else {
                errorMessage = "连接超时";
            }

            //6.下载POS机信息数据
            System.out.println("上次posInfos更新时间" + posInfoLastUpdateDate);
            parameters.clear();
            parameters = new HashMap<>();
            parameters.put("cnt", downloadCNT);
            parameters.put("lastUpdateDate", posInfoLastUpdateDate);
            so = WebServiceUtil.getResponse(config, "DownPosInfo", parameters, 1000 * 60 * 10);

            if (so != null) {
                SoapPrimitive sp = (SoapPrimitive) so.getProperty("DownPosInfoResult");
                WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                if (wsResult.getResultCode() == 0) {
                    //保存
                    List<POSInfo> posInfos = new ArrayList<POSInfo>();
                    List<Map<String, Object>> values = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                    for (Map<String, Object> map : values) {
                        POSInfo posInfo = new POSInfo();
                        posInfo.setPOSId(map.get("POS_ID").toString());
                        posInfo.setPOSCode(map.get("POS_CODE").toString());
                        posInfo.setPOSName(map.get("POS_NAME").toString());
                        posInfo.setIsTeraminal(map.get("IS_TERMINAL").toString());
                        posInfo.setStatus(map.get("STATUS").toString());
                        posInfo.setUpdate(map.get("UPDATE_DATE").toString());

                        //System.out.println("posInfo:" + posInfo.toString());

                        posInfos.add(posInfo);
                    }
                    System.out.println("下载posInfos信息：" + posInfos.size());
                    if (posInfos.size() > 0) {
                        POSInfoDao.savePOSInfoList(posInfos);
                    }
                } else if (wsResult.getResultCode() == 3 || wsResult.getResultCode() == 4) {
                    errorMessage = wsResult.getResultValues().get("message").toString();
                }
            } else {
                errorMessage = "连接超时";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return errorMessage;
    }

}
